<?php

namespace App\Admin\Controllers;

use App\Admin\Exports\PayOrderExport;
use App\Http\Controllers\Controller;
use App\Model\AppChannel;
use App\Model\AppVersion;
use App\Model\PayOrder;
use App\Model\User;
use App\Model\UserProfile;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Layout\Content;

class PayOrderController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */

    public function index()
    {
        $this->adminId = Admin::user()->id;
        $this->super = $this->adminId == 1;
        return Admin::content(function (Content $content) {
            $content->header('充值订单');
            $content->description('');
            $content->body($this->grid());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $payStatus = [PayOrder::STATUS_OK, PayOrder::STATUS_EXTRA];
        $grid = new Grid(new PayOrder());
        if (request()->userProfile && isset(request()->userProfile['user_profile_id'])) {
            request()->offsetUnset('status');
            $grid->model()->whereIn('status', $payStatus)->orderBy('id', 'desc')->orderBy('finished_at', 'desc');
        } elseif (request()->status == null && !request()->wx_mch_id) {
            request()->merge(['status' => PayOrder::STATUS_OK]);
            $grid->model()->orderBy('id', 'desc')->orderBy('finished_at', 'desc');
        } else {
            $grid->model()->orderBy('id', 'desc')->orderBy('finished_at', 'desc');
        }
        // if (!request()->finished_at) {
        //     request()->merge(['finished_at' => ['start' => date('Y-m-d'), 'end' => '']]);
        // }
        // $where = [
        // ['status', PayOrder::STATUS_OK],
        // ['finished_at', '>', date('Y-m-d')]
        // ];
        // $grid->model()->with('userProfile')->with('userItem')->with('subject')->orderBy('id', 'desc')->orderBy('finished_at', 'desc');
        $grid->order_id('内部订单号');
        $grid->out_trade_no('三方订单');
        $grid->userItem()->phone('手机号');
        $grid->userProfile()->user_profile_id('用户ID');
        $grid->userProfile()->nick_name('昵称');
        $grid->userItem()->channel('注册渠道')->display(function ($role) {
            if (!$this->userItem) return '-';
            $data = json_decode($this->userItem->appChannel, true);
            return $data['channel_name'] ?? '未知渠道';
        });
        $grid->userItem()->version('当前版本');
        $grid->total_amount('支付金额（元）')->display(function ($data) {
            return $data / 100;
        })->totalRow(function ($amount) {
            $amount /= 100;
            return "<span class='text-danger text-bold'><i class='fa fa-yen'></i> 总充值：{$amount}元</span>";
        });
        $grid->recharge_coin('充值金币')->display(function ($data) {
            return $data > 0 ? "{$data}金币" : '-';
        });
        $grid->send_coin('充值赠送金币');
        $grid->created_at('支付发起时间')->display(function ($time) {
            return !$time ? '-' : date('Y-m-d H:i:s', strtotime($time));
        });
        $grid->finished_at('支付完成时间');
        $grid->channel('支付渠道')->display(function ($data) {
            return PayOrder::CHANNEL[$data];
        });
        $grid->wx_mch_id('商户号');
        $grid->status('支付结果')->display(function ($data) use ($payStatus) {
            return in_array($data, $payStatus) ? '支付成功' : PayOrder::STATUS[$data];
        });

        //禁用导出
        // $grid->disableExport();
        $grid->exporter(new PayOrderExport($grid));
        //禁用行选择
        $grid->disableRowSelector();
        $grid->disableActions();
        $grid->disableCreateButton();
        $grid->filter(function ($filter) {
            // $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('order_id', '订单号');
                $filter->equal('channel', '支付渠道')->select(PayOrder::CHANNEL);
                $filter->equal('userItem.channel', '注册渠道')->select(AppChannel::getChannels());
                $filter->like('userItem.phone', '手机号');
                $filter->between('total_amount', '订单金额（分）');
            });
            $filter->column(1 / 2, function ($filter) {
                $status = PayOrder::STATUS;
                if (!$this->super) unset($status[PayOrder::STATUS_EXTRA]);
                $filter->equal('out_trade_no', '第三方商户订单');
                $filter->equal('status', '充值结果')->select($status);
                $filter->between('finished_at', '充值时间')->datetime();
                $filter->equal('userProfile.user_profile_id', '充值用户ID');
                $filter->between('userProfile.created_at', '注册时间')->datetime();
            });
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableAll();
        });
        return $grid;
    }
}
